{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[-0.6162],\n",
       "        [-1.4793],\n",
       "        [ 0.7924],\n",
       "        [-1.1414],\n",
       "        [ 1.2091]])"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "v_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "\n",
    "n = 5  # number of nodes\n",
    "v_lower = torch.zeros((n, 1))\n",
    "v_upper = torch.ones((n, 1))\n",
    "v_pred = torch.rand((n, 1)) \n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor(0.)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn.functional as F\n",
    "\n",
    "def inequality_loss(v_pred, v_lower, v_upper):\n",
    "    \"\"\"\n",
    "    Computes the loss for inequality constraints v_lower <= v_pred <= v_upper.\n",
    "    \n",
    "    Arguments:\n",
    "    v_pred -- predicted vector of size 5x1\n",
    "    v_lower -- lower bound vector of size 5x1\n",
    "    v_upper -- upper bound vector of size 5x1\n",
    "    \n",
    "    Returns:\n",
    "    loss -- the computed loss\n",
    "    \"\"\"\n",
    "    # Compute violation of lower bound\n",
    "    violation_lower = torch.relu(v_lower - v_pred)\n",
    "    \n",
    "    # Compute violation of upper bound\n",
    "    violation_upper = torch.relu(v_pred - v_upper)\n",
    "    \n",
    "    # Compute the total violation\n",
    "    total_violation = torch.sum(violation_lower) + torch.sum(violation_upper)\n",
    "    \n",
    "    # Compute the hinge loss\n",
    "    hinge_loss = F.relu(total_violation)\n",
    "    \n",
    "    return hinge_loss\n",
    "\n",
    "\n",
    "\n",
    "inequality_loss(v_pred, v_lower, v_upper)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pinss",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.16"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
